package com.alkaid.anime.service.impl;

import com.alibaba.fastjson.JSON;
import com.alkaid.anime.mapper.CommentMapper;
import com.alkaid.anime.mapper.UserMapper;
import com.alkaid.anime.service.CommentService;
import com.alkaid.anime.utils.RedisUtils;
import com.alkaid.commons.core.CacheKeyDefinition;
import com.alkaid.commons.entity.Comment;
import com.alkaid.commons.entity.User;
import com.alkaid.commons.ex.UnknownErrorException;
import com.alkaid.commons.utils.SnowflakeIdWorker;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author Kylin
 */
@Service
public class CommentServiceImpl implements CommentService {

    private final CommentMapper commentMapper;

    private final UserMapper userMapper;

    private final RedisUtils redisUtils;

    public CommentServiceImpl(CommentMapper commentMapper, UserMapper userMapper, RedisUtils redisUtils) {
        this.commentMapper = commentMapper;
        this.userMapper = userMapper;
        this.redisUtils = redisUtils;
    }

    @Override
    public List<Comment> getComments(Integer animeId) throws UnknownErrorException {
        String key = CacheKeyDefinition.getCommentKey(animeId);
        List<Comment> commentList =
                JSON.parseArray(JSON.toJSONString(redisUtils.getList(key, 0L, -1L)), Comment.class);
        if (commentList == null || commentList.size() == 0) {
            commentList = commentMapper.findComments(animeId);
            if (commentList == null || commentList.size() == 0) {
                return commentList;
            }
            redisUtils.lrPushs(key, CacheKeyDefinition.CACHE_TIME_DEFAULT, commentList.toArray());
        }
        return commentList;
    }

    @Override
    public void addComment(Comment select) throws UnknownErrorException {
        if ("".equals(select.getContent())) {
            return;
        }
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 3);
        select.setId(idWorker.nextId());
        select.setSendTime(new Date());
        Integer result = commentMapper.insert(select);
        if (result < 1) {
            throw new UnknownErrorException("发表评论失败");
        }
        String key = CacheKeyDefinition.getCommentKey(select.getAnimeId());
        List<Comment> commentList =
                JSON.parseArray(JSON.toJSONString(redisUtils.getList(key, 0L, -1L)), Comment.class);
        if (!(commentList == null || commentList.size() == 0)) {
            User userSelect = new User();
            userSelect.setId(select.getUserId());
            User user = userMapper.selectById(userSelect);
            select.setNickname(user.getNickname());
            select.setAvatar(user.getAvatar());
            redisUtils.llPush(key, CacheKeyDefinition.CACHE_TIME_DEFAULT, select);
        }
    }
}
